<?php


namespace app\api\controller\apply;


use app\BaseController;



use app\Request;
use broadcast\services\UtilService as Util;

/**
 * Class Index
 * @package app\api\controller
 */
class LuckDraw extends BaseController
{
    //奖品列表
    public function lst(Request $request)
    {
        $list = showPrizeList();
        return app("json")->fail($list);
    }

    //抽奖
    public function smoke(Request $request)
    {
        $uid = $request->uid();
        if (strpos($uid, 'yk') !== false) return app("json")->success('游客状态无法发送红包');
        session('website', $request->website());
        $list = showPrizeList();
        $prize = $this->rankPrize($list);
        $whether = $this->reward($prize,$uid);
        unset($prize['weight']);
        unset($prize['type']);
        return $whether ? app("json")->success($prize) : app("json")->fail("抽奖失败");
    }




    //进行抽奖
    public function rankPrize ($prize)
    {
        $result = []; // 初始化响应数组
        $weight = []; // 初始化权重数组

        foreach ($prize as $key => $val) {
            $weight[$key] = $val['weight']; // 权重数据放入数组
        }

         // 概率数组的总概率
         $weightSum = array_sum($weight); // 权重总和
         asort($weight); // 排序
         // 权重数组循环
         foreach ($weight as $k => $v) {
             $randNum = mt_rand(1, $weightSum); // 生成一个随机数
             if ($randNum <= $v) {
                 $result = $prize[$k]; // 如果随机数小于等于当前权重,结束循环，数据放入响应数据内
                 break;
             } else {
                 $weightSum -= $v; // 权重总和减去当前权重
             }
         }
         return $result; // 数据返回
    }

    //获取奖励
    public function reward ($prize,$uid)
    {
        switch ($prize['type']) {
            case "gold":
                return true;
                break;
            default:
                return true;
                break;
        }
    }
}